<?php

declare(strict_types=1);

namespace App\Command;

use App\Constants\CacheKey;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Support\Filesystem\Filesystem;
use PHPUnit\Event\Runtime\PHP;
use function Hyperf\Support\env;

require_once(BASE_PATH . '/app/Libs/Helper.php');

/**
 * 批量导入到内存中
 */
#[Command]
class SaveRedisCommand extends HyperfCommand
{
    protected $logger;
    protected $config;

    public function __construct(StdoutLoggerInterface $logger, ConfigInterface $config)
    {
        $this->logger = $logger;
        $this->config = $config;

        // 定义命令行名称
        parent::__construct('save:redis');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('批量保存缓存');
    }

    public function handle()
    {
        ini_set('memory_limit', '-1');
        $startTime = ceil(getMicrotime());
        $fs = new Filesystem();
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\Redis::class);

        $this->line('1.开始保存日语姓名到内存');
        $files = $fs->allFiles(BASE_PATH . '/storage/ja_names/');
        if (empty($files)) {
            $this->logger->error(BASE_PATH . '/storage/ja_names目录下没有文件');
            return \Hyperf\Command\Command::FAILURE;
        }
        $total = count($files);
        foreach ($files as $sk => $file) {
            $filepath = $file->getRealPath();
            $filename = $file->getFilename();
            if (!str_ends_with($filename, '.txt')) {
                continue;
            }
            $fileid = str_replace('.txt', '', $filename);
            $sj = $sk + 1;
            $this->line('  开始导入' . $sj . '/' . $total . '，name=' . $filename);
            $content = file_get_contents($filepath);
            $names = explode(PHP_EOL, trim($content, PHP_EOL));
            if (!empty($content)) {
                $redis->set('janame:' . $fileid, json_encode($names, JSON_UNESCAPED_UNICODE));
            }
        }

        $this->line('2.开始将商品ID归到二级分类中');
        $res = Db::table('categories')->select("*")->where('level', 2)->get()->toArray();
        if (empty($res)) {
            $this->logger->error('分类数据不存在');
        }
        $dir = BASE_PATH . '/storage/cate2pids/';
        if (!$fs->isDirectory($dir)) {
            $fs->makeDirectory($dir, 0755, true);
        }
        foreach ($res as $item) {
            $cateId2 = intval($item->id);
            $catePids = Db::select("select id from products where cate_id2={$cateId2}");
            if (!empty($catePids)) {
                $this->line('  开始生成cateid2=' . $cateId2 . '得产品ID的数据,datime=' . date('Y-m-d H:i:s'));
                $cateid2pids = [];
                foreach ($catePids as $sitem) {
                    $cateid2pids[] = intval($sitem->id);
                }
                $cateid2pids = array_unique($cateid2pids);
                $cateTxt = $dir . $cateId2 . '.txt';
                $fs->put($cateTxt, join(',', $cateid2pids));
            }
        }

        $endTime = ceil(getMicrotime());
        $huafei = $endTime - $startTime;

        $this->line('已经全部保存完成，共花费' . $huafei . '秒，程序退出');
        return \Hyperf\Command\Command::SUCCESS;
    }
}
